import '@ant-design/compatible/assets/index.css';
import {
  CheckCircleOutlined,
  FormOutlined,
  LockOutlined,
  PhoneOutlined,
  SolutionOutlined,
  UserOutlined,
} from '@ant-design/icons';
import { Button, Card, Form, Input, message, Result, Steps } from 'antd';
import { FormInstance } from 'antd/lib/form';
import { connect } from 'dva';
import React, { Component } from 'react';
import Link from 'umi/link';
import md5 from '../../../../node_modules/js-md5';
import styles from './style.less';
import { specicalChars } from '@/support/constant/common';
import { validateContinuousChar } from '@/utils/validator';

const FormItem = Form.Item;
const { Step } = Steps;
class ResetPassword extends Component<any, any> {
  formRef = React.createRef<FormInstance>();

  constructor(props: any) {
    super(props);
    this.state = {
      current: 0,
      count: 0,
      rules: {},
      captchaCheck: false,
      saveData: {},
      captchaLoadding: false,
    };
  }

  componentWillUnmount(): void {
    clearInterval(this.interval);
  }
  // 下一步
  nextStep = () => {
    const { current } = this.state;
    this.setState({ current: current + 1 });
  };

  // 获取验证码
  onGetCaptcha = () => {
    const { dispatch } = this.props;
    this.setState({ captchaLoadding: true });
    const errorList: any = this.formRef.current?.getFieldError();
    if (errorList.length > 0) {
      return;
    }
    this.formRef.current
      ?.validateFields()
      .then(values => {
        dispatch({
          type: 'login/sendCaptcha',
          payload: { userMobile: values.userMobile, accountName: values.accountName },
          callback: (response: any) => {
            this.setState({ captchaLoadding: false });
            if (response.statusCode === '0') {
              message.success('发送成功！');
              this.setState({ captchaCheck: true });
              this.handleGetRules();
              let count = 60;
              this.interval = setInterval(() => {
                count -= 1;
                this.setState({ count });
                if (count === 0) {
                  clearInterval(this.interval);
                }
              }, 1000);
            } // end if
          }, // end callback
        });
      })
      .catch(errorInfo => {
        this.setState({ captchaLoadding: false });
      });
  };
  // 获取密码输入规则
  handleGetRules = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'extend/fetch',
      payload: { url: '/account/findpasswordstrategy' },
      callback: (response: any) => {
        this.setState({ rules: response.data });
      },
    });
  };
  // 校验确认密码
  checkPassword = (rule: any, value: any) => {
    const {
      rules: { passwordStrategy, passwordStrategyDesc },
    } = this.state;
    if (value) {
      const regex = new RegExp(passwordStrategy);
      if (!regex.test(value)) {
        return Promise.reject(`请确认输入的密码，${passwordStrategyDesc}`);
      }
    } else {
      return Promise.reject('请输入密码！');
    }
    return Promise.resolve();
  };

  // 校验密码
  checkPwd = (rule: any, value: any) => {
    const {
      rules: { passwordStrategy, passwordStrategyDesc },
    } = this.state;
    const regex = new RegExp(passwordStrategy);
    if (value) {
      if (!regex.test(value)) {
        return Promise.reject(`请输入正确的密码，${passwordStrategyDesc}`);
      }else if(/([\dA-Za-z])\1{3,}/.test(value)) {
        return Promise.reject('禁止密码设置4位连续相同的字符');
      } else if(validateContinuousChar(value)) {
        return Promise.reject('禁止密码设置4位连续递增，递减的数字或字母');
      } else if(specicalChars.some(char => value.toLowerCase().indexOf(char.toLowerCase()) > -1 )) {
        return Promise.reject('禁止密码设置4位1qaz,2wsx,3edc,dfm,admin,dftc,dfrd,等简单字符');
      }
    } else {
      return Promise.reject('请输入密码！');
    }
    return Promise.resolve();
  };

  // 点击下一步触发
  handleNext = () => {
    const { current, saveData } = this.state;
    this.setState({ captchaCheck: true });
    const { dispatch } = this.props;
    this.formRef.current
      ?.validateFields()
      .then(values => {
        // 处于第一步，校验并存取数据,否则提交数据
        if (current === 0) {
          this.setState({ saveData: values });
          this.nextStep();
        } else {
          const submitData = {
            ...saveData,
            ...values,
            newAccountPwd: md5(values.newAccountPwd),
            newAccountPwdCheck: md5(values.newAccountPwdCheck),
          };
          dispatch({
            type: 'login/resetPassword',
            payload: { ...submitData },
            callback: (response: any) => {
              this.nextStep();
            },
          });
        }
      })
      .catch(errorInfo => {});
  };
  // 点击上一步触发
  handlePre = () => {
    const { current } = this.state;
    this.setState({ current: current - 1, captchaCheck: false, saveData: {} });
    setTimeout(() => this.formRef.current?.resetFields(), 200);
  };

  render() {
    const { loading } = this.props;
    const { current, count, captchaCheck, captchaLoadding } = this.state;
    const captchaBtn = (
      <Button
        disabled={count}
        type="primary"
        style={{ width: '100%' }}
        onClick={() => this.onGetCaptcha()}
        loading={captchaLoadding}
      >
        {count ? `${count}s后重试` : '验证码'}
      </Button>
    );
    const firstStep = (
      <div>
        <FormItem
          name="accountName"
          label="登录账号"
          labelCol={{ span: 5 }}
          rules={[
            {
              required: true,
              message: '数字、字母、中文或特殊符号组成的2-12位字符!',
              whitespace: true,
              max: 12,
              min: 2,
            },
          ]}
        >
          <Input
            prefix={<UserOutlined style={{ color: 'rgba(0,0,0,.25)' }} />}
            placeholder="请输入登录账号"
          />
        </FormItem>
        <FormItem
          name="userMobile"
          label="手机号码"
          labelCol={{ span: 5 }}
          rules={[
            {
              required: true,
              pattern: /^1\d{10}$/,
              message: '手机号格式错误,手机号为11位纯数字！',
            },
          ]}
        >
          <Input
            prefix={<PhoneOutlined style={{ color: 'rgba(0,0,0,.25)' }} />}
            placeholder="请输入手机号码"
          />
        </FormItem>
        <FormItem
          name="verifCode"
          label="验证码"
          labelCol={{ span: 5 }}
          rules={[{ required: captchaCheck, pattern: /^\d{4}$/, message: '请输入验证码！' }]}
        >
          <Input maxLength={4} placeholder="请输入验证码" addonAfter={captchaBtn} />
        </FormItem>
        <Button
          type="primary"
          style={{ width: '100%' }}
          onClick={() => this.handleNext()}
          disabled={!captchaCheck}
        >
          下一步
        </Button>
      </div>
    );

    const secondStep = (
      <div>
        <FormItem
          name="newAccountPwd"
          label="输入新密码"
          labelAlign="left"
          hasFeedback
          rules={[{ required: captchaCheck, validator: this.checkPwd }]}
        >
          <Input.Password prefix={<LockOutlined />} maxLength={30} placeholder="请输入新密码" />
        </FormItem>
        <FormItem
          name="newAccountPwdCheck"
          dependencies={['newAccountPwd']}
          hasFeedback
          label="确认新密码"
          labelAlign="left"
          rules={
            [
            { 
              required: captchaCheck,
              validator: this.checkPassword
            },
            ({ getFieldValue }) => {
              return {
                  validator(_, value) {
                    if (!value || getFieldValue('newAccountPwd') === value) {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error('两次输入的密码不匹配！'));
                  },
                }
              },
          ]
          }
        >
          <Input.Password prefix={<LockOutlined />} maxLength={30} placeholder="请确认输入的密码" />
        </FormItem>
        <Button
          type="primary"
          loading={loading}
          onClick={() => this.handleNext()}
          style={{ width: '100%' }}
        >
          确 认
        </Button>
      </div>
    );

    const thirdStep = (
      <Result
        className={styles.result}
        status="success"
        title={<span>密码重置成功，请重新{<Link to="/user/login">登录</Link>}</span>}
      />
    );

    const steps = [
      {
        title: '验证账号',
        icon: <SolutionOutlined />,
        content: firstStep,
      },
      {
        title: '找回密码',
        icon: <FormOutlined />,
        content: secondStep,
      },
      {
        title: '完成',
        icon: <CheckCircleOutlined />,
        content: thirdStep,
      },
    ];
    return (
      <div className={styles.resetPassword}>
        <Card bordered={false}>
          <Steps current={current} style={{ width: '90%', marginLeft: 20, marginTop: 25 }}>
            {steps.map(item => (
              <Step key={item.title} title={item.title} icon={item.icon} />
            ))}
          </Steps>
          <div className={styles.stepsContent}>
            <Form ref={this.formRef}>{steps[current].content}</Form>
          </div>
          <Link style={{ float: 'right', marginTop: 5 }} to="/user/login">
            <span style={{ color: '#2F54EB' }}>已有账号，去登录！</span>
          </Link>
        </Card>
      </div>
    );
  }
}

export default connect(({ login, loading }: any) => ({
  login,
  loading: loading.effects['login/resetPassword'],
}))(ResetPassword);
